package com.springboot.demo.seria_deseria.config;

import com.springboot.demo.seria_deseria.core.CommonContext;
import com.springboot.demo.seria_deseria.core.CountryEnum;
import com.springboot.demo.seria_deseria.core.UserInfoDto;
import com.springboot.demo.seria_deseria.util.CountryUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

@Component
@Slf4j
public class HeaderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws IOException {
        // 不传country-id，则默认为 墨西哥
        CountryUtil.notIgnoreCountry();
        boolean b = CountryUtil.isIgnoreCountry();
        log.info("CountryUtil.isIgnoreCountry() = {}", b);
        String countryIdStr = request.getHeader(UserInfoDto.Country_ID);
        // country-id 存入上下文中
        if(StringUtils.isBlank(countryIdStr)){
            CountryUtil.setCountryId(CountryEnum.Mexico.getCountryId());
        } else {
            CountryEnum countryEnum = CountryEnum.getItem(Integer.parseInt(countryIdStr));
            CountryUtil.setCountryId(countryEnum.getCountryId());
        }

        log.info("*** start *** countryId: {}, url：{} ", CountryUtil.getCountryId(), request.getRequestURI());

        //api 监控白名单处理
//        String reqUrl=request.getRequestURI();
//        reqUrl=reqUrl.replaceFirst("//","/");
//        log.info("request-id: {}",request.getAttribute("request-id"));
//        log.info("request url(interceptor): {}",reqUrl);
//        log.info("device type: {}",deviceTypeStr);

//        if(isWhiteListApi(reqUrl)){
//            String clientToken = request.getHeader(UserInfoDTO.Client_Token);
//            Integer userId= UserTokenManager.getUserId(clientToken);
//            String reqId= request.getAttribute("request-id").toString();
//            String method=request.getMethod();
//
//            String reqJson="";
//            if(HttpMethod.GET.name().equals(method)){
//                reqJson = parseGetRequest(request);
//            }else {
//                reqJson = parsePostRequest(request);
//            }
//
//            MallLogClientAccessParam logParam=new MallLogClientAccessParam();
//            if(StringUtils.isNotBlank(countryIdStr)){
//                logParam.setCountryId(Integer.valueOf(countryIdStr));
//            }
//
//            if(StringUtils.isNotBlank(deviceTypeStr)){
//                logParam.setDeviceType(Integer.valueOf(deviceTypeStr));
//            }
//
//            logParam.setReqParam(reqJson);
//            logParam.setAccessIp(IpUtil.getIpAddr(request));
//
//            if(null!=userId){
//                logParam.setUserId(userId);
//            }
//
//            logParam.setAccessUrl(reqUrl);
//            logParam.setReqId(reqId);
//            logParam.setReqType(method);
//
//            String url= LogServiceProperties.host+LogServiceProperties.mallLogClientAccessAdd;
//            String json = JsonUtil.toJson(logParam);
//            OkHttpUtil.postJsonParams(url, json);
//        }

        return true;//注意 这里必须是true否则请求将就此终止。
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,  @NonNull Object handler, Exception ex) {
        CommonContext.clear();
        boolean b = CountryUtil.isIgnoreCountry();
        log.info("CountryUtil.isIgnoreCountry() = {}", b);
        log.info("*** end *** countryId: {}, 接口：{} 结束请求", CountryUtil.getCountryId(), request.getRequestURI());
    }

    private String parseGetRequest(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        String json="{";
        sb.append(json);
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String paramValue = request.getParameter(paramName);
            json=String.format("'%s':'%s',",paramName,paramValue);
            sb.append(json);
        }

        // 有入参的情况去除最后一个逗号
        if(sb.length()>1){
            String finalJson=String.format("%s}",sb.substring(0,sb.length()-1));
            return finalJson;
        }

        return "";
    }

//    private String parsePostRequest(HttpServletRequest request) throws IOException {
//        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
//
//        return wrapper.getBody();
//    }

//    private boolean isWhiteListApi(String url){
//        boolean isWhiteApi=false;
//
//        String[] whiteApis= PropertiesUtil.get().getMonitorApi().split(",");
//        List<String> whiteList= Arrays.stream(whiteApis).toList();
//        if(whiteList.contains(url)){
//            isWhiteApi=true;
//        }
//
//        return isWhiteApi;
//    }

    public static void main(String[] args) {
        String reqUrl="//wx/order/detail/v7";
        reqUrl=reqUrl.replaceFirst("//","/");

        System.out.println("reqUrl: "+reqUrl);
    }

}
